package com.dxtan90.strategy.impl;

import com.dxtan90.strategy.BaseStrategy;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author shijunhao
 * @since 2024/4/16 14:03
 */
public class Quyushuwu extends BaseStrategy {

    @Override
    public String getSourceUrl() {
        return "https://www.quyushuwu.xyz";
    }

    @Override
    public String getCategoryName() {
        return "quyushuwu";
    }

    @Override
    public String parseTitle(Document document) {
        return Optional.ofNullable(document.select("h1.lh1d2"))
                .map(element -> element.get(0))
                .map(Element::text)
                .orElse("noneTitle_" + System.currentTimeMillis());
    }

    @Override
    public List<String> parseCategory(Document document) {
        Elements ol = Optional.ofNullable(document.getElementById("chapterList"))
                .map(Element::children)
                .orElse(new Elements());
        List<String> category = new ArrayList<>();
        for (Element li : ol) {
            Optional.of(li.child(0)).ifPresent(a -> {
                String href = a.attr("href");
                category.add(href.substring(getSourceUrl().length()));
            });
        }
        return category;
    }

    @Override
    public List<String> parseContent(Document document) {
        List<String> sectionList = new ArrayList<>();
        String title = Optional.ofNullable(document.getElementById("mlfy_main_text"))
                .map(element -> element.child(0))
                .map(Element::text)
                .orElse("");
        sectionList.add(title);
        String text = Optional.ofNullable(document.getElementById("TextContent"))
                .map(Element::html)
                .orElse("");
        String[] split = text.replaceAll(" ", "").split("<br>");
        for (String s : split) {
            sectionList.add(Jsoup.parse(s).text());
        }
        return sectionList;
    }

}